import { routerReducer as routing } from 'react-router-redux'
import { combineReducers } from 'redux'
import { FETCH_QUESTION_LIST, FETCH_QUESTIONS, RESTORE_QUESTION_LIST, INIT_ALL_OPTION_CACHE, OPTION_SELECTED } from '../constants/actionTypes'

function testGroupReducer(state = {
    loading: true
}, action) {
    let loading = action.loading || false;
    switch (action.type) {
        case FETCH_QUESTION_LIST:
            return Object.assign({}, state, {
                loading: loading,
                status: action.status,
                data: action.data,
                error: action.error
            });
        default:
            return state
    }
}

function questionReducer(state = {
    loading: true
}, action) {
    let loading = action.loading || false;
    switch (action.type) {
        case FETCH_QUESTIONS:
        case RESTORE_QUESTION_LIST:
            return Object.assign({}, state, {
                loading: loading,
                status: action.status,
                data: action.data,
                error: action.error
            });
        default:
            return state
    }
}

//处理选项选中
function optionReducer(state = {
    data: []
}, action) {
    switch (action.type) {
        case INIT_ALL_OPTION_CACHE:
            return {
                data: action.data
            };
        case OPTION_SELECTED:
            let cData = action.data,
                obj = {};
            obj.index = action.index;
            obj.questionType = action.questionType;
            obj.selectedItem = action.selectedItem;
            obj.score = action.score;
            cData[action.index] = obj;
            return {
                data: cData
            };
        default:
            return state
    }
}

const rootReducer = combineReducers({
    testGroupReducer,
    questionReducer,
    optionReducer,
    routing
});

export default rootReducer;
